package spring.my.suveng.jdbc.originJDBC;

import java.sql.*;

/**
 * @author Veng Su 1344114844@qq.com
 * @date 2018/8/14 21:03
 */

public class DBUtils {
    private String url;
    private String username;
    private String password;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        DBUtils dbUtils=new DBUtils();
        dbUtils.setUrl("jdbc:mysql://localhost:3306/suveng?serverTimezone=Asia/Shanghai&characterEncoding=utf8");//TODO:相应需要改变自己的值
        dbUtils.setUsername("root");//TODO : 改成自己的用户名
        dbUtils.setPassword("root");//TODO: 改成自己的密码
//        1. 加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2. 获得数据库连接
        Connection conn = DriverManager.getConnection(dbUtils.getUrl(), dbUtils.getUsername(), dbUtils.getPassword());
        //3.操作数据库，实现增删改查
        //预编译SQL，减少sql执行
        String sql="INSERT INTO user (name, age) VALUES ('suveng', 22)";
        PreparedStatement  stmt = conn.prepareStatement(sql);
        stmt.executeUpdate();

        ResultSet rs2 = stmt.executeQuery("SELECT * FROM user");
        //如果有数据，rs.next()返回true
        while(rs2.next()){
            System.out.println(rs2.getString("name")+" 年龄："+rs2.getInt("age"));
        }
    }
}
